<?php
global $AppUI, $m;
//
$uid = $AppUI->user_id;
$perms =& $AppUI->acl();
$canEdit = $perms->checkModuleItem('quotations', 'edit');
if (!$canEdit) {
	$AppUI->setMsg( 'Access denied', UI_MSG_ERROR, true );
	$AppUI->redirect();
}

require_once($AppUI->getMasterDataClass('mdstatus'));
require_once('quotation_histories.class.php');
// create a new instance of the einstein class
$obj = new CQuotations();
$msg = '';	// reset the message string

// detect if a delete operation has to be processed
$del = dPgetParam($_POST, 'del', 0);

// detect if a cancel operation has to be processed
$cancel = dPgetParam($_POST, 'cancel', 0);

$active_act = dPgetParam($_POST, 'statusActive', 0);
$unactive_act = dPgetParam($_POST, 'statusUnActive', 0);
$complete_act = dPgetParam($_POST, 'statusComplete', 0);

$quote_id = intval(isset($_POST['quote_id']) ? $_POST['quote_id']: $_GET['quote_id']);
// TODO: Check permission role
// Check edit
$denyEdit = getDenyEdit($m, $quote_id);
// Check create
$denyAdd = !getPermission($m, 'add');
// Check view
$denyDelete = false;//!getPermission($m, 'delete', $quote_id);

// Action cancel
if($cancel){
	$AppUI->redirect();
}
else if($del){
	// Delete Quotation
	if((!$quote_id) or $denyDelete) {
		//$AppUI->setMsg( $msg, UI_MSG_ERROR );
		//$AppUI->redirect();
		echo 'fail';
	}
	else{
		if ($msg = $obj->delete($quote_id)){
			//$AppUI->setMsg( $msg, UI_MSG_ERROR );
			//$AppUI->redirect();
			echo 'fail';
		}else{
			//$AppUI->setMsg( "Quote deleted", UI_MSG_ALERT);
			//$AppUI->redirect("m=quotations");
			echo 'success';
		}
	}
}
else if($active_act){
	// Used on page quote_view
	if((0 < $quote_id) and !$denyEdit){
		$tmp = $_POST['quote_start_date'];
		$quote_start_date = substr($tmp, 0, 4) . '-'.substr($tmp, 4, 2) . '-'.substr($tmp, 6, 2) . ' 00:00:00';
		$tmp = $_POST['quote_expire_date'];
		$quote_expire_date = substr($tmp, 0, 4) . '-'.substr($tmp, 4, 2) . '-'.substr($tmp, 6, 2) . ' 00:00:00';

		$obj->quote_id = $quote_id;
		$obj->load($quote_id);
		// Check line list

		// Get Id of object status has code equal ACTIVE_KEY
		$active_key = dPgetSysVal(ACTIVE_KEY);
		$objMD = new CMdStatus();
		$objMD->loadByCode($active_key['code']);
		$obj->quote_status = $objMD->status_id;
		$obj->quote_start_date = $quote_start_date;
		$obj->quote_expire_date = $quote_expire_date;
		//$obj->quote_completed = ACTIVE_VAL;
		$msg = $obj->store();
		echo 'successful';
	}
	else{
		echo $quote_id;
		echo 'failed';
	}
}
else if($complete_act){
	// Used on page quote_view
	if((0 < $quote_id) and !$denyEdit){
		$obj->quote_id = $quote_id;
		// Check line list

		// Get Id of object status has code equal ACTIVE_KEY
		$complete_key = dPgetSysVal(COMPLETED_KEY);
		$objMD = new CMdStatus();
		$objMD->loadByCode($complete_key['code']);
		$obj->quote_status = $objMD->status_id;
		//$obj->quote_completed = COMPLETED_VAL;
		$msg = $obj->store();
		echo 'successful';
	}
	else{
		echo $quote_id;
		echo 'failed';
	}
}
else if($unactive_act){
	// Used on page quote_view
	$update_fail = true;
	if((0 < $quote_id) and !$denyEdit){
		$obj->quote_id = $quote_id;
		// Check line list

		// Get Id of object status has code equal PROPOSED_KEY
		$proposed_key = dPgetSysVal(PROPOSED_KEY);
		$objMD = new CMdStatus();
		$objMD->loadByCode($proposed_key['code']);

		// Backup quotation to quotation_history
		$row = $obj->getQuotationById($uid, $quote_id);
		// TODO: check $row
		if(is_array($row) and (count($row) > 0)){
			$quote_obj = $row[0];
			if($quote_obj['quote_completed'] == ACTIVE_VAL){				
				// Load Quotation history
				$quote_his = new CQuotation_histories();
				$quote_his->qhis_fkid = intval($quote_id);
				$quote_his->qhis_data = addslashes(serialize($quote_obj));
				$quote_his->qhis_version = $obj->quote_version; 
				$quote_his->store();
				
				// Reset status come back to default status				
				$sql = "UPDATE quotations SET quote_start_date=NULL, quote_expire_date=NULL, quote_status=" . $objMD->status_id . ", quote_completed=0 WHERE quote_id=".$obj->quote_id;
				db_exec($sql);
				$update_fail = false;
				echo 'successful';
			}
		}
	}
	if($update_fail){
		echo $quote_id;
		echo ' failed';
	}
	exit;
}
else{
	// bind the informations (variables) retrieved via post to the quotations object
	$isNotNew = @$_POST['quote_id'];
	// Check validate: customer and supplier
	$validate = true;
	$extra = array();
	if(!isset($_POST['quote_customer']) || (intval($_POST['quote_customer']) < 1)){
		$AppUI->setMsg("You must input value for quotation customer", 0, true);
		$validate = false;
	}
	// Check duplicate code
	$quote_code = isset($_POST['quote_code'])?trim(addslashes($_POST['quote_code'])):"";
	if(strlen($quote_code) > 0){
		$extra["where"] = "quote_code like '%{$quote_code}%'";
		if(isset($quote_id) and intval($quote_id)){
			$extra["where"] .= "AND quote_id != {$quote_id}";
		}
		$code_list = $obj->getAllowedRecords($uid, "quote_code", "", null, $extra);
		if(is_array($code_list) and count($code_list) > 0){
			$AppUI->setMsg("[{$quote_code}] was exist. Quotation's code is not duplicate, please try new string", 1, true);
			$validate = false;
		}
	}
	else{
		$AppUI->setMsg("You must input value for quotation code", 1, true);
		$validate = false;
	}
	if(!$validate){
		$AppUI->redirect('m=quotations&a=quote_crud');
	}
	else if(!$obj->bind($_POST)){
	 	$AppUI->setMsg( $obj->getError(), UI_MSG_ERROR );
	}
	else{
		if($isNotNew and $denyEdit){
			$AppUI->setMsg( $msg, UI_MSG_ERROR );
		}
		elseif((!$isNotNew) and $denyAdd){
			$AppUI->setMsg( $msg, UI_MSG_ERROR );
		}
		else{
			$msg = $obj->store();
			$AppUI->setMsg( $isNotNew ? "Quotation [{$obj->quote_code}] {$obj->quote_name} has been updated" : "Quotation [{$obj->quote_code}] {$obj->quote_name} has been added", UI_MSG_OK, true );
			$AppUI->redirect("m=quotations&a=quote_view&quote_id={$obj->quote_id}");
			exit;
		}
	}
	$AppUI->redirect();
}
?>
